﻿Option Explicit On
Imports System.IO

Module database
    Public cn As New ADODB.Connection
    Public rs As New ADODB.Recordset

    Public Function field(ByVal nome) As String
        If (rs.Fields.Item(nome).Value Is DBNull.Value) Then
            field = ""
        Else
            field = rs.Fields.Item(nome).Value
        End If
    End Function

    Public Sub connetti(ByVal file As String)
        With cn
            .ConnectionString = "Provider=Microsoft.Jet.OleDB.4.0;Data source=" & file
            '.ConnectionString = "Provider=Microsoft.Jet.OleDB.4.0;Data source=db.mdb"
            .ConnectionTimeout = 5 'numero dei secondi di timeout
            .CursorLocation = ADODB.CursorLocationEnum.adUseClient 'tipo di cursore
            .Mode = ADODB.ConnectModeEnum.adModeShareDenyNone 'nessuna limitazione
            .Open() 'apertura ricordarsi di chiuderla
        End With
        With rs
            .ActiveConnection = cn ' imposta a che connessione si riferisce
            .LockType = ADODB.LockTypeEnum.adLockOptimistic ' imposta il tipo di lock
        End With
    End Sub

    Sub query(ByVal q As String)
        If rs.State = 1 Then rs.Close()
        rs.Open(q)
    End Sub

    Function exportAllenamento(ByVal fileName As String) As Boolean
        Dim fs As StreamWriter

        Try
            If Not File.Exists(fileName) Then
                fs = New StreamWriter(File.Create(fileName))
            Else
                fs = New StreamWriter(New FileStream(fileName, FileMode.Truncate))
            End If

            query("SELECT * FROM allenamento")
            While Not rs.EOF
                Dim riga As String = ""
                For Each f As ADODB.Field In rs.Fields
                    riga &= f.Value & ";"
                Next
                fs.WriteLine(riga.Substring(0, riga.Length - 1))
                rs.MoveNext()
            End While

            fs.Close()
            exportAllenamento = True
        Catch ex As Exception
            exportAllenamento = False
        End Try
    End Function

End Module
